﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Project.Module.DAO.IBL;
using Project.Module.Model;
using Project.Engine.Utilities;

namespace Project.Module.DAO.BL
{
    public class CartBL : IBLTable<Cart, int>
    {
        public List<GioHangModel> GetListByCustomerId(int id)
        {
            var queryCart = from e in this.Context.Carts
                            join a in this.Context.Products
                            on e.ProductID equals a.ProductID
                            where e.CustomerID == id && (
                                (e.IsDelivery == null || (e.IsDelivery != null && e.IsDelivery == true)) // da thanh toan
                            )
                            select new GioHangModel()
                            {
                                idCart = e.CartID,
                                idProduct = e.ProductID,
                                CustomerId = e.CustomerID,
                                nameProduct = a.ProductName,
                                priceProduct = a.Price,
                                quantityProduct = e.Quantity != null ? e.Quantity.Value : 0,
                                money = e.Quantity != null ? a.Price * e.Quantity.Value : 0,
                                status = e.IsDelivery == true ? "Đã thanh toán" : "Chưa thanh toán",
                                CreatedDate = e.CreatedDate.HasValue ? e.CreatedDate.Value : Convert.ToDateTime("01/01/1900"),
                            };

           
            if (queryCart != null && queryCart.ToList().Count > 0)
            {
                return queryCart.ToList();
            }
            else
            {
                return null;
            }
        }

        public int GetNumberCartByCustomerId(int id)
        {
            int total = 0;
            var query = from e in this.Context.Carts
                        where e.CustomerID == id
                       && ((e.IsCheckOut == null || (e.IsCheckOut != null && e.IsCheckOut == false)) &&
                                (e.IsDelivery == null || (e.IsDelivery != null && e.IsDelivery == false)))
                        select new
                        {
                            ProductId = e.ProductID,
                            CustomerId = e.CustomerID
                        };

            if (query != null)
            {
                total = ConvertUtil.ToInt32(query.ToList().Count);
            }

            return total;
        }

        public void DeleteCart(string username, int idCart)
        {
            int idCustomer = (new CustomerBL()).GetIdByUsername(username);
            Cart cart = this.Context.Carts.Single(c => c.CustomerID == idCustomer && c.CartID == idCart);
            this.Context.Carts.DeleteOnSubmit(cart);
            this.Context.SubmitChanges();
        }

        public void AddCart(string username, int idProduct)
        {
            int idCustomer = (new CustomerBL()).GetIdByUsername(username);
            int quantity = GetQuantity(idCustomer, idProduct);

            // neu quantity = 1; chua co trong gio hang; add vao gio hang 
            if (quantity == 1)
            {
                int id = GetMaxId() + 1;
                string sql = @"insert into Cart (
                                CartID, ProductID, CustomerID, IsDelivery, Quantity
                           ) values ( {0}, {1}, {2}, cast('0' as bit), cast('1' as int))";
                var query = this.Context.ExecuteQuery<CartModel>(sql, new object[] { id, idProduct, idCustomer }).ToList();
            }
            // quantity > 1; san pham da co trong gio hang; update so luong san pham trong gio hang
            else
            {
                // id cua gio hang
                int idCard = GetIDByCustomerAndProduct(idCustomer, idProduct);

                if (idCard != 0)
                {
                    string sql = @"update Cart set Quantity = {0} where CartID = {1}";
                    var query = this.Context.ExecuteQuery<CartModel>(sql, new object[] { quantity, idCard }).ToList();
                }
            }
        }

        public void BuyCart(string username, int idCart)
        {
           // if (idCart > 0)
           // {
                //insert to Order table ! 
               // int idCustomer = (new CustomerBL()).GetIdByUsername(username);
               // this.Context.Carts.Single(c => c.CustomerID == idCustomer && c.IsDelivery == false).IsDelivery = true;
                //this.Context.Carts.Single(c => c.CustomerID == idCustomer && c.CartID == idCart).IsCheckOut = true;
                //                int Orderid = GetMaxId() + 1;
                //                string sql = @"insert into Order (
                //                                OrderID, CustomerID, ProductID, IsDelivery, Quantity
                //                           ) values ( {0}, {1}, {2}, cast('0' as bit), cast('1' as int))";
                //                var query = this.Context.ExecuteQuery<CartModel>(sql, new object[] { id, idProduct, idCustomer }).ToList();
             //   this.Context.SubmitChanges();
           // }

                int idCustomer = (new CustomerBL()).GetIdByUsername(username);
                string sql = @"update Cart set IsDelivery = 1 where [CustomerID] = {0} and IsDelivery = 0";
                var query = this.Context.ExecuteQuery<CartModel>(sql, new object[] { idCustomer }).ToList();
              

        }

        public int GetMaxId()
        {
            int Id = 0;
            var query = from e in this.Context.Carts
                        orderby e.CartID descending
                        select new { Id = e.CartID };

            if (query != null)
            {
                Id = ConvertUtil.ToInt32(query.Select(c => c.Id).FirstOrDefault().ToString());
            }

            // return
            return Id;
        }

        public void DeleteCartInCMS(int idCart)
        {
            Cart cart = this.Context.Carts.Single(c => c.CartID == idCart);
            this.Context.Carts.DeleteOnSubmit(cart);
            this.Context.SubmitChanges();
        }
        //chi tiet don hang
        public void ChitietInCMS(int idCart)
        {
            Cart cart = this.Context.Carts.Single(c => c.CartID == idCart);
            // this.Context.Carts.DeleteOnSubmit(cart);
            this.Context.SubmitChanges();
        }

        public CartModel GetDetailOrder(int id){
            var query = from e in this.Context.Carts
                        where e.CartID == id
                        select new CartModel() { 
                            CartID = e.CartID,
                            CustomerID = e.CustomerID,
                            ProductID = e.ProductID,
                        };
            if (query != null)
            {
                return query.FirstOrDefault();
            }
            else { return null; }
        }

        private int GetQuantity(int customerID, int productId)
        {
            var query = from e in this.Context.Carts
                        where e.CustomerID == customerID && e.ProductID == productId && e.IsDelivery == false && e.IsCheckOut == false
                        select new { quantity = e.Quantity };
            if (query != null)
            {
                // neu co san pham; tang so luong len 1
                return Convert.ToInt32(query.Select(c => c.quantity).FirstOrDefault()) + 1;
            } // = 1; ko co san pham
            else
            {
                return 1;
            }
        }
        //get customer name from customer id at cart table 
        public string GetCustomerName(int cartID)
        {
            var query = from e in this.Context.Customers
                        join b in this.Context.Carts on e.CustomerID equals b.CustomerID
                        select new { customerName = e.Firstname + e.Lastname };
            if (query != null)
            {
                return Convert.ToString(query.Select(c => c.customerName).FirstOrDefault());
            }
            else
            {
                return null;
            }
        }
        private int GetIDByCustomerAndProduct(int customerID, int productId)
        {
            var query = from e in this.Context.Carts
                        where e.CustomerID == customerID && e.ProductID == productId
                        select new { id = e.CartID };
            if (query != null)
            {
                return Convert.ToInt32(query.Select(c => c.id).FirstOrDefault());
            }
            else
            {
                return 0;
            }
        }
    }
}
